package com.jgp.security.service;

import com.jgp.security.config.SecUserAdapter;
import com.jgp.security.pojo.UserInfo;
import com.jgp.security.secmodel.SecInstitution;
import com.jgp.security.secmodel.SecLoginLog;
import com.jgp.security.secmodel.SecRole;
import com.jgp.security.secrepository.SecLoginLogRepository;
import com.jgp.sys.query.Operator;
import com.jgp.sys.query.OrderList;
import com.jgp.sys.query.QueryFilterList;
import com.jgp.sys.ui.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2022/2/18
 */
@Service
@Transactional(transactionManager = "secondTransactionManager", readOnly = true)
public class SecLoginLogService {
	
	@Autowired
	private SecUserAdapter userAdapter;
	
	@Autowired
	private SecLoginLogRepository repository;
	
	@Transactional(transactionManager = "secondTransactionManager")
	public void record() {
		UserInfo user = userAdapter.currentUser();
		SecLoginLog loginLog = new SecLoginLog();
		loginLog.setUserId(user.getId());
		loginLog.setAccount(user.getUsername());
		String roles = user.getRoles().stream().map(SecRole::getName).collect(Collectors.joining(","));
		String institutions = user.getInstitutions().stream().map(SecInstitution::getName).collect(Collectors.joining(","));
		loginLog.setRoles(roles);
		loginLog.setInstitutions(institutions);
		repository.create(loginLog);
	}
	
	public Long countLoginTimes(String userId) {
		QueryFilterList filters = new QueryFilterList();
		filters.addFilter("userId", Operator.eq, userId);
		return repository.count(filters);
	}
	
	public Long countLoginTimes(String userId, LocalDateTime start, LocalDateTime end) {
		QueryFilterList filters = new QueryFilterList();
		filters.addFilter("userId", Operator.eq, userId);
		filters.addFilter("createDatetime", Operator.ge, start);
		filters.addFilter("createDatetime", Operator.le, end);
		return repository.count(filters);
	}
	
	public List<SecLoginLog> query(QueryFilterList filters, OrderList orders, Pager pager) {
		return repository.read(filters, orders, pager);
	}
}
